package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.atguigu.spzx.exception.BaseException;
import com.atguigu.spzx.manager.mapper.CategoryBrandMapper;
import com.atguigu.spzx.manager.service.ICategoryBrandService;
import com.atguigu.spzx.model.vo.common.dto.product.CategoryBrandDto;
import com.atguigu.spzx.model.vo.common.entity.product.Brand;
import com.atguigu.spzx.model.vo.common.entity.product.CategoryBrand;
import com.atguigu.spzx.model.vo.common.page.PageInfo;
import com.atguigu.spzx.model.vo.common.vo.product.CategoryBrandVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 分类品牌 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-02-29
 */
@Service
@RequiredArgsConstructor
public class CategoryBrandServiceImpl extends ServiceImpl<CategoryBrandMapper, CategoryBrand> implements ICategoryBrandService {
    /**
     * 分页条件查询分类品牌数据
     * @param categoryBrandDto
     * @param page
     * @param limit
     * @return
     */
    private final CategoryBrandMapper categoryBrandMapper;
    public PageInfo<CategoryBrandVo> selectByPage(CategoryBrandDto categoryBrandDto, Long page, Long limit) {
        //1.设置pageNum,和pageSize
        Page<CategoryBrand> categoryBrandPage = new Page<>(page, limit);
        //2.查询数据data
        List<CategoryBrandVo> categoryBrandVoList =  categoryBrandMapper.page(categoryBrandPage,categoryBrandDto);
        PageInfo<CategoryBrandVo> categoryBrandVoPageInfo = new PageInfo<>();
        //3.记录分页查询基本信息
        BeanUtil.copyProperties(categoryBrandPage,categoryBrandVoPageInfo);
        //4.设置data数据,返回
        categoryBrandVoPageInfo.setRecords(categoryBrandVoList);
        return categoryBrandVoPageInfo;
    }

    /**
     * 添加分类品牌
     * @param categoryBrand
     */
    @Transactional
    public void add(CategoryBrand categoryBrand) {
        //id值为空，避免重复id
        categoryBrand.setId(null);
        boolean isSuccess = save(categoryBrand);
        if(!isSuccess) throw new BaseException("添加失败");
    }

    /**
     * 修改分类品牌
     * @param categoryBrand
     */
    @Transactional
    public void update(CategoryBrand categoryBrand) {
        if(categoryBrand==null||categoryBrand.getId()==null){
            throw new BaseException("参数不合法");
        }
        categoryBrandMapper.updateCategoryBrand(categoryBrand);
    }

    /**
     * 根据分类id查询品牌数据
     * @param categoryId
     * @return
     */
    public List<Brand> getBrandByCategoryId(Long categoryId) {
        return categoryBrandMapper.selectBrandByCategoryId(categoryId);
    }


}
